// API请求封装
export const BASE_URL = 'http://localhost:8891' // 后端API地址

// 请求拦截器
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 显示加载提示（除非明确指定不显示）
    if (options.showLoading !== false) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
    }

    // 获取token
    const token = uni.getStorageSync('token')

    // 组装请求头，避免无 token 时发送 Authorization 触发预检
    const headers = {
      'Content-Type': 'application/json',
      ...options.header
    }
    if (token) {
      headers['Authorization'] = `Bearer ${token}`
    }

    // 请求配置
    const config = {
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      timeout: 180000, // 3分钟超时 (180000毫秒)
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        ...options.header
      },
      success: (res) => {
        if (options.showLoading !== false) {
          uni.hideLoading()
        }

        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data)
          } else {
            // 业务错误
            uni.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else if (res.statusCode === 401) {
          // 未授权，跳转到登录页
          uni.removeStorageSync('token')
          uni.navigateTo({
            url: '/pages/login/login'
          })
          reject(res)
        } else {
          // 其他错误
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.hideLoading()

        // 检查是否是超时错误
        if (err.errMsg && err.errMsg.includes('timeout')) {
          uni.showToast({
            title: '请求超时，请稍后重试',
            icon: 'none',
            duration: 3000
          })
        } else {
          uni.showToast({
            title: '网络连接失败',
            icon: 'none'
          })
        }
        if (options.showLoading !== false) {
          uni.hideLoading()
        }
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(err)
      }
    }

    uni.request(config)
  })
}

// GET请求
export const get = (url, data = {}) => {
  return request({
    url,
    method: 'GET',
    data
  })
}

// GET请求（不显示加载提示，用于定时请求）
export const getSilent = (url, data = {}) => {
  return request({
    url,
    method: 'GET',
    data,
    showLoading: false
  })
}

// POST请求
export const post = (url, data = {}, params = {}) => {
  // 如果有URL参数，添加到URL中
  if (Object.keys(params).length > 0) {
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    url += (url.includes('?') ? '&' : '?') + queryString
  }

  return request({
    url,
    method: 'POST',
    data
  })
}

// PUT请求
export const put = (url, data = {}) => {
  return request({
    url,
    method: 'PUT',
    data
  })
}

// DELETE请求
export const del = (url, data = {}) => {
  return request({
    url,
    method: 'DELETE',
    data
  })
}

export default request
